from rest_framework import serializers

from erp_system.models import DeptModel


class ChildDeptSerializer(serializers.ModelSerializer):
    children = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = DeptModel
        fields = ['id', 'name', 'parent', 'children']

    def get_children(self, obj):
        if obj.children:
            return ChildDeptSerializer(instance=obj.children, many=True).data
        return None


class DeptSerializer(serializers.ModelSerializer):
    """
    部门的序列化器
    """
    children = ChildDeptSerializer(read_only=True, many=True)

    class Meta:
        model = DeptModel
        fields = ['id', 'name', 'parent', 'children']
